package cn.edu.sdjzu.cs.dingcan.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.sdjzu.cs.dingcan.entity.FoodType;
import cn.edu.sdjzu.cs.dingcan.utils.JdbcUtils;

public class FoodTypeDao {
	private final Logger logger = LoggerFactory.getLogger(FoodTypeDao.class);
	
	private final QueryRunner queryRunner = JdbcUtils.getQueryRunner();
	private final ResultSetHandler<FoodType> foodTypeHandler = new ResultSetHandler<FoodType>(){
		@Override
		public FoodType handle(ResultSet rs) throws SQLException {
			if(!rs.next()) {
				return null;
			}
			return new FoodType(rs.getLong("id"), rs.getString("type_name"));
		}
	};
	private final ResultSetHandler<List<FoodType>> foodTypeListHandler = new ResultSetHandler<List<FoodType>>(){
		@Override
		public List<FoodType> handle(ResultSet rs) throws SQLException {
			List<FoodType> result = new ArrayList<>();
				FoodType foodType;
				do {
					foodType = foodTypeHandler.handle(rs);
					if (foodType != null) {
						result.add(foodType);
					}
				} while (foodType != null);
				return result;
		}
	};
	public int add(FoodType foodType) {
		String sql = "INSERT INTO foodtype(type_name) VALUES(?);";
		try {
			return this.queryRunner.update(sql, foodType.getTypeName());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(Long id) {
		String sql = "DELETE FROM foodtype WHERE id=?";
		try {
			this.queryRunner.update(sql, id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void updata(FoodType foodType) {
		String sql = "UPDATE foodtype SET type_name= ? WHERE id = ?";
		try {
			queryRunner.update(sql, foodType.getTypeName(), foodType.getId());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<FoodType> findAll() {
		String sql = "SELECT * FROM foodtype";
		try {
			return queryRunner.query(sql, foodTypeListHandler);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public FoodType getFoodTypeById(Long id) throws SQLException {
		String sql = "SELECT * FROM foodtype WHERE id = ?";		
		return this.queryRunner.query(sql, foodTypeHandler, id);
	}

	public List<FoodType> query(String keyword) throws SQLException {
		String sql = "SELECT * FROM foodtype WHERE type_name LIKE ?";
		return this.queryRunner.query(sql, foodTypeListHandler, "'%" + keyword + "'%");
	}

	// public Integer getFirstType() {
	// 	try {
	// 		String sql = "SELECT * FROM foodtype LIMIT 1";
	// 		return queryRunner.query(sql, new ScalarHandler<Integer>());
	// 	} catch (Exception e) {
	// 		throw new RuntimeException(e);
	// 	}
	// }
}
